package util.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class WebServiceHelper {
	public static int BUFFER_LEN = 1024;

	/**
	 * 把消息发到指定的url上。
	 * 
	 * @param 指定的url
	 * @param 消息
	 * @return web返回的msg
	 * @throws IOException
	 */
	public static String post(String urlname, String msg) throws IOException {
		// TODO
		URL url = new URL(urlname + "?" + msg);

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		// 设置读取的时间
		conn.setReadTimeout(1000 /* milliseconds */);

		// 设置连接的时间
		conn.setConnectTimeout(1000 /* milliseconds */);
		conn.setRequestMethod("GET");

		conn.setDoInput(true);
		// conn.setDoOutput(true);

		// TODO

		// OutputStream os = conn.getOutputStream();
		// os.write(msg.getBytes());
		conn.connect();

		int len = 0;
		byte bt[] = new byte[BUFFER_LEN];

		InputStream is = conn.getInputStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		while ((len = is.read(bt)) != -1) {
			out.write(bt, 0, len);
		}

		return out.toString();
	}

	/**
	 * 判断网络是否连接
	 * 
	 * @param context
	 *            上下文
	 * @return true 有连接网络, false 没有连接网络
	 */
	public static boolean isconnected(Context context) {
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected())
			return true;
		else
			return false;
	}
}
